package com.xxh.gateway.filter;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.nimbusds.jose.JWSObject;
import com.xxh.common.constant.AuthConstants;
import com.xxh.common.utils.RedisUtil;
import com.xxh.common.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.Charset;
import java.text.ParseException;
import java.util.List;


/**
 * 网关设置全局过滤器的目的主要是解析token，转发给下面的微服务的。
 * 同时可以也考虑设置一个黑名单的功能。
 */
@Component
public class AuthGlobalFilter implements GlobalFilter, Ordered {
    AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Autowired
    RedisUtil redisUtil;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        // 无token放行
        String token = request.getHeaders().getFirst(AuthConstants.JWT_TOKEN_HEADER);
        if (StrUtil.isBlank(token)) {
            return chain.filter(exchange);
        }

        try {
            JWSObject jwsObject = JWSObject.parse(token);
            String payload = jwsObject.getPayload().toString();
            JSONObject jsonObject = JSONUtil.parseObj(payload);

            //检查黑名单内是否有这个小伙子
            String jti = jsonObject.getStr(AuthConstants.JWT_JTI_KEY);
            Boolean isBlack = redisUtil.hasKey(AuthConstants.TOKEN_BLACKLIST_PREFIX + jti);
            if (isBlack) {
                return writeFailedToResponse(response);
            }
            // 存在token且不是黑名单，request写入JWT的载体信息
            request = exchange.getRequest().mutate()
                    .header(AuthConstants.JWT_PAYLOAD_KEY, payload)
                    .build();
            exchange = exchange.mutate().request(request).build();
            return chain.filter(exchange);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        //放行
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }



    public static Mono writeFailedToResponse(ServerHttpResponse response){
        response.setStatusCode(HttpStatus.OK);
        response.getHeaders().set(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
        response.getHeaders().set("Access-Control-Allow-Origin", "*");
        response.getHeaders().set("Cache-Control", "no-cache");
        Result result = new Result();
        result.put("msg","你被加入了黑名单，好好反省一下你干了啥");
        String body = JSONUtil.toJsonStr(result);
        DataBuffer buffer = response.bufferFactory().wrap(body.getBytes(Charset.forName("UTF-8")));
        return response.writeWith(Mono.just(buffer))
                .doOnError(error -> DataBufferUtils.release(buffer));
    }
}
